package com.yunhai.device.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

import javax.annotation.Resource;

/**
 * consumer 消费者，对收到的消息进行处理
 */
//@Component
@Slf4j
public class MessageCallback implements MqttCallbackExtended {


    private MqttClient client;

    private String topic;


    private MqttConnectOptions mqttConnectOptions;



    @Resource
    private MqttMsgHandle mqttMsgHandle;

    public MessageCallback() {
    }

    public MessageCallback(MqttClient mqttClient, String topic, MqttConnectOptions mqttConnectOptions,MqttMsgHandle mqttMsgHandle) {
        this.client = mqttClient;
        this.topic = topic;
        this.mqttConnectOptions = mqttConnectOptions;
        this.mqttMsgHandle = mqttMsgHandle;
    }

    // 在客户端连接断开时触发
    @Override
    public void connectionLost(Throwable throwable) {

        if (client != null && !client.isConnected()) {
            log.info("{}, 连接断开，正在reconnect....", client.getClientId());
            try {
                client.reconnect();
                // client.connect(this.mqttConnectOptions);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            log.info("未知异常，连接断开");
        }


    }
    // 在客户端与服务器连接成功时触发
    @Override
    public void connectComplete(boolean b, String url) {
        log.info("{} 上线了{} {}", client.getClientId(), b, url);
        try {
//            client.subscribe(this.topic, 0);
            //拉茶机数据
            client.subscribe("/PullTea/+/send/data", 1);
            //拉茶机告警数据
            client.subscribe("/PullTea/+/send/alarm", 1);
            //拉茶机wifi信号数据
            client.subscribe("/PullTea/+/send/netsign", 1);

            //奶茶机日常报表
            client.subscribe("/MilkTea/+/send/data", 1);
            //奶茶机报警数据
            client.subscribe("/MilkTea/+/send/alarm", 1);

        } catch (MqttException e) {
            e.printStackTrace();
        }


    }
    // 在客户端收到订阅的消息时触发
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {

        //收集到了 devicetype, deviceId
        TopicEntity topicEntity = MqttTopicHandle.handleTopic(topic);
        topicEntity.setQos(message.getQos());
        log.info("接收消息主题 : " + topic);
        log.info("接收消息内容 : " + new String(message.getPayload()));
        //获取到消息内容

        try {
            String msg = new String(message.getPayload());
            JSONObject jsonObject = JSON.parseObject(msg);
            String cmd = jsonObject.getString("cmd");
            topicEntity.setCmd(cmd);

            if( cmd.equals("upload_netsign") ){
                //处理上传的网络信号
                mqttMsgHandle.handlePullTeaDeviceUploadNetSign(topicEntity,jsonObject);
            }
            else if( cmd.equals("upload_state") ){
                //封装需要返回的 topic
                mqttMsgHandle.handleDeviceUpdateState( topicEntity, jsonObject);
            }
            else if( cmd.equals("upload_alarm") ){
                mqttMsgHandle.handleDeviceUpdateAlarm(topicEntity, jsonObject);
            }
            else if(  cmd.equals("update_pkg") ){

                //封装需要返回的 topic
                topicEntity.setSendTopic("/"+topicEntity.getDeviceType()+"/"+topicEntity.getDeviceId()+"/receive");
                //获取版本号
                String fwVer = jsonObject.getString("fwVer");
                mqttMsgHandle.handlePkgUpdate(this.client, topicEntity, fwVer);
                return;
            }
            else if( cmd.equals("update_pkg_item") ){
                //封装需要返回的 topic
                topicEntity.setSendTopic("/"+topicEntity.getDeviceType()+"/"+topicEntity.getDeviceId()+"/receive");
                //获取版本号
                String fwVer = jsonObject.getString("fwVer");
                //获取序列号
                String index = jsonObject.getString("index");
                mqttMsgHandle.handlePkgItemUpdate(this.client, topicEntity, fwVer, index);
                return;

            //上传状态数据
            }


        } catch (Exception e) {
            log.error("JSON Format Parsing Exception : {}", e);
        }
     }
    // 在客户端发送消息至服务器成功时触发
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("消息发送完成：---------" + token.isComplete());
    }
}